package com.smallkingson.ylib.net.http;

import java.util.List;
import java.util.Set;

import android.content.Context;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v4.util.LruCache;

import com.smallkingson.ylib.core.Yr;
import com.smallkingson.ylib.db.YSQLites;
import com.smallkingson.ylib.db.cache.YCacher;
import com.smallkingson.ylib.net.http.bean.Request;
import com.smallkingson.ylib.net.http.bean.Response;

public class YHttpCacher extends YCacher<Request, Response> {

	public static final long DEFAULT_ALIVE_SECOND = 60 * 60 * 24 * 30;

	private static final String TABLE_NAME_RESPONSE = Response.class
			.getSimpleName();

	private static MemoryLruCache memoryLruCache;

	private static YHttpCacher cacher;

	public static YHttpCacher getInstance(Context context) {

		if (cacher == null) {
			synchronized (YHttpCacher.class) {
				if (cacher == null) {
					cacher = new YHttpCacher(context);
				}
			}
		}
		return cacher;
	}

	private YHttpCacher(Context context) {
		init(context);
	}

	private static void cacheToMemory(Response response) {
		Yr.d("缓存内存 ：" + response.getCacheKey());
		memoryLruCache.put(response.getCacheKey(), response);
	}

	@Override
	public void clear(String like) {
		Set<String> keys = memoryLruCache.snapshot().keySet();

		//清除缓存
		for(String key:keys){
			if(key.matches(".*"+like+".*")){
				Yr.d("删除内存：" +key);
				memoryLruCache.remove(key);
			}
		}
		super.clear("cacheKey like '%"+like+"%'");
	}

	public Response getResponseFromMemory(String cacheKey) {

		return memoryLruCache.get(cacheKey);
	}

	public static class MemoryLruCache extends LruCache<String, Response> {

		public MemoryLruCache(int maxSize) {
			super(maxSize);
		}
	}

	@Override
	public Class<?> getBeanClass() {
		return Response.class;
	}

	@Override
	public void cache(Response response) {

		try {
			cacheToMemory(response);
			int count = YSQLites.getCount(helper, Response.class, "cacheKey='"
					+ YSQLites.sqliteEscape(response.getCacheKey()) + "'");
			if (count > 0) {
				YSQLites.delete(helper, Response.class, "cacheKey='?'",
						response.getCacheKey());
			}
			Yr.d("缓存本地 ：" + response.getCacheKey());
			YSQLites.insert(helper, response);
		} catch (Exception e) {
			Yr.logError(e);
		}

	}

	@Override
	public Response getCache(Request request) {

		String cacheKey = request.getKey();

		if (cacheKey == null) {
			return null;
		}

		Response response = getResponseFromMemory(cacheKey);

		if (response != null) {
			response.from = YHttps.From.MEMORY;
			Yr.i("来自 MEMORY : KEY:   " + request.getCacheKey() + ", URL: "
					+ request.getUrl());
			return response;
		}

		try {
			List<Response> list = YSQLites.select(helper, Response.class,
					"cacheKey='?'", new Object[]{YSQLites.sqliteEscape(request.getKey())});
			if (list != null && list.size() > 0) {
				Yr.i("来自 DISK : KEY:   " + request.getCacheKey() + ", URL: "
						+ request.getUrl());
				response = list.get(0);

				if (response.getTime() + response.getAliveSecond() * 1000 < System
						.currentTimeMillis()) {
					Yr.i("[YHttp]超时：" + request.getCacheKey() + ", URL: "
							+ request.getUrl());
					response = null;
				} else {
					response.from = YHttps.From.DISK;
					cacheToMemory(response);
				}
			}
			return response;

		} catch (Exception e) {
			Yr.logError(e);
		}
		return response;
	}

	@Override
	protected void onInit(SQLiteOpenHelper helper) {
		super.onInit(helper);
		memoryLruCache = new MemoryLruCache(200);
	}
}
